import axios from "axios";
import { ElLoading } from 'element-plus'
import router from "@/router";
const request = axios.create({
    baseURL: import.meta.env.VITE_BASE_URL,
    timeout: 1000 * 20,
    headers: { 'X-Custom-Header': 'foobar' }
});
// 添加请求拦截器
let loading
request.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    config.headers.Authorization=localStorage.getItem('accessToken')
    return config;
}, function (error) {
    // 对请求错误做些什么
    setTimeout(() => {
        loading.close()
    }, 500)
    return Promise.reject(error);
});

// 添加响应拦截器
request.interceptors.response.use(async function (response) {
    // 2xx 范围内的状态码都会触发该函数。
    setTimeout(() => {
        loading.close()
    }, 500)
    if (response.status == 200 && response.data.code == 401) {
        const res = await request.get('/refreshToken', {
            params: {
                refreshToken: localStorage.getItem('refreshToken')
            }
        })
        const accessToken = res.data.data.accessToken
        localStorage.setItem('accessToken', accessToken)
        response.config.headers.Authorization = accessToken
        return request(response.config)
    }
    // 对响应数据做点什么
    return response;
}, function (error) {
    // 超出 2xx 范围的状态码都会触发该函数。
    setTimeout(() => {
        loading.close()
    }, 500)
    if(error.response.status>200&&error.response.status<300){
        return Promise.reject('200'+error.response.status);
    }else if(error.response.status>=300&&error.response.status<400){
        return Promise.reject('300'+error.response.status);
    }else if(error.response.status>=400&&error.response.status<500){
        if(error.response.status==401){
            localStorage.removeItem('accessToken')
            localStorage.removeItem('refreshToken')
            router.push('/login')
        }
        return Promise.reject('400'+error.response.status);
    }else if(error.response.status==500){
        return Promise.reject('500'+error.response.status);
    }
    // 对响应错误做点什么
    return Promise.reject(error);
});
setInterval(async () => {
    try {
        const res = await request.get('/refreshToken', {
            params: {
                refreshToken: localStorage.getItem('refreshToken')
            }
        })
        localStorage.setItem('accessToken', res.data.data.accessToken)
    }catch(e){
        console.log('111',e);
        
    }
  },1000*60*5)
export default request